<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/28
 * Time: 14:15
 */

namespace app\Service;


use app\api\model\VideoUser\VideoUserLikeModel;
use think\facade\Db;

class UserLike extends BaseService
{
    /**
     * @param $user 用户
     * @param int $video_id 视频ID
     * @param int $status 0：取消 1：点赞
     */
    public function save(array $user, int $video_id, int $status): bool
    {
        if (VideoUserLikeModel::finds($video_id, $user['id'])) {
            Db::transaction(function () use ($user, $video_id, $status) {
                if ($status == 1) {
                    Db::name('video_user')->where('id', $video_id)->inc('nums_like', 1)->update(); //点赞加1
                } else {
                    Db::name('video_user')->where('id', $video_id)->dec('nums_like', 1)->update(); //点赞减 1
                }
                VideoUserLikeModel::where(['video_id' => $video_id, 'uid' => $user['id']])->update(['status' => $status]);
            });
            return true;
        }
        Db::transaction(function () use ($user, $video_id, $status) {
            VideoUserLikeModel::insert(['video_id' => $video_id, 'uid' => $user['id'], 'status' => $status]);
            Db::name('video_user')->where('id', $video_id)->inc('nums_like', 1)->update(); //点赞加1
        });
        return true;
    }
}